package com.youzhi.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.youzhi.backend.dto.CommonConstant;
import com.youzhi.backend.entity.Letter;
import com.youzhi.backend.mapper.LetterMapper;
import com.youzhi.backend.request.UpdateLetterRequest;
import com.youzhi.backend.service.ILetterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youzhi.backend.service.IUserSessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 后台信件表 服务实现类
 * </p>
 *
 * @author xumeng
 * @since 2023-02-13
 */
@Slf4j
@Service
public class LetterServiceImpl extends ServiceImpl<LetterMapper, Letter> implements ILetterService {


    @Autowired
    private IUserSessionService userSessionService;

    @Override
    public Map<String, Long> getUnReadNum() {
        Object userId = userSessionService.getCurrentUserAttr(IUserSessionService.attr_userId);
        QueryWrapper<Letter> wrapper = new QueryWrapper<>();
        wrapper.eq(Letter.Fields.receiveUserId, userId.toString());
        wrapper.eq(Letter.Fields.isRead, CommonConstant.NO);
        wrapper.eq(Letter.Fields.isDeleted, CommonConstant.NO);
        long count = count(wrapper);
        Map<String, Long> map = new HashMap<>();
        map.put("num", count);
        return map;
    }

    /**
     * 更新信件
     *
     * @param request
     */
    @Override
    public void updateLetter(UpdateLetterRequest request) {

        UpdateWrapper<Letter> objectUpdateWrapper = new UpdateWrapper<>();
        objectUpdateWrapper.eq(Letter.Fields.id, request.getLetterId());
        objectUpdateWrapper.set(Letter.Fields.isRead, request.getIsRead());
        objectUpdateWrapper.set(Letter.Fields.isDeleted, request.getIsDeleted());
        objectUpdateWrapper.set(Letter.Fields.updateTime, new Date());

        update(objectUpdateWrapper);
    }

}
